package com.charles.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.charles.common.CommonResult;
import com.charles.common.entity.Payment;
import com.charles.springcloud.alibaba.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: 风中灵劲草
 * @Date: 2021/08/27/17:12
 * @Description:
 */
@RestController
@Slf4j
public class CircleBreakerController {

    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Value("${server.port}")
    private String serverPort;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private PaymentService paymentService;

    @GetMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback" , fallback = "handlerFallback")  //fallback只负责业务异常
    public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/getPayment/" + id, CommonResult.class);
        if (result.getData() == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应记录");
        }
        return result;
    }

    public CommonResult handlerFallback(@PathVariable("id") Long id , Throwable e){
        return new CommonResult(444,"兜底异常handlerFallback,异常内容:" + e.getMessage());
    }

    @GetMapping("/consumer/feign/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        CommonResult<Payment> result = paymentService.getPaymentById(id);
        return result;
    }
}
